import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;


public class PacketAssembler implements IPacketAssembler {

  static final String classLabel = "PacketAssembler: ";
  TreeMap<Integer,Packet> theMessage;
  
	/**
	 * Default Constructor for PacketAssembler, intializes treeMap
	 */
  public PacketAssembler(){
	  theMessage=new TreeMap<Integer, Packet>();
  }
  
  /**
   * Method reads packets from a file and puts them in a tree map with the packetID as the key and the packet itself
   * as the value.
   */
	@Override
	public void readPackets(Scanner inFile) {
		// TODO Auto-generated method stub
		
		while(inFile.hasNext()){
			Packet thePacket=new Packet();
			
			thePacket=thePacket.readPacket(inFile);
			
			theMessage.put(thePacket.getPacketID(), thePacket);
		}
	}

	/**
	 * Method prints the contents of the sorted tree to the outFile by transferring the keys to a set than iterating over that set
	 * and printing the Packet that corresponds with that key.
	 */
	@Override
	public void writePackets(PrintWriter outFile) {
		// TODO Auto-generated method stub
		Set<Integer> theTree=theMessage.keySet();
		
		Iterator<Integer> iterate=theTree.iterator();
		
		while(iterate.hasNext()){
			int theKey=iterate.next();
			FileUtils.logFile.println(classLabel+"	inside iteration		"+ theKey);
			outFile.println(classLabel+"	"+theKey +"	'	"+theMessage.get(theKey).toString());
			
		}
		outFile.close();
		
	}

}
